﻿using System;
using System.Data;
using System.Web.UI;
using System.Xml.Xsl;
using BLL;
using ET;
using Ext.Net;
using HTML;
using Roles;

namespace ERP.Modules
{
    public partial class Districts : UserControl
    {
        private readonly Districts_BLL _clsDistricts = new Districts_BLL();
        private readonly Province_BLL _clsProvince = new Province_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetData();
                Province();
                GetComboBox();
                ClearTextBox();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }

        //-------Store-Datasource-----------------
        protected void StoreDistricts_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxDistrictsProvince.Text = string.Empty;
            GetData();
            Province();
        }

        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsDistricts.Show();
        }

        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grDistricts.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    GetComboBox();
                    ClearTextBox();
                    DataDetail(int.Parse(row.RecordID));
                    WindowsDistricts.Show();
                    sm.UpdateSelection();
                }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grDistricts.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        Districts_BLL.DeleteDistricts(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        clsFormat.Alert_ERROR("Thông Báo",
                            "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetData();
        }
        protected void SelectBoxDistrictsProvince_Change(object sender, DirectEventArgs e)
        {
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtDistricts_ID.Text == string.Empty)
            {
                InsertDistricts();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateDistricts();
                }
            }
        }

        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsDistricts.Close();
        }

        //----------Click-------------------
        protected void DistrictsDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Districts_Id = int.Parse(e.ExtraParams["Districts_Id"]);
            DataDetail(Districts_Id);
            WindowsDistricts.Show();
        }

        #region[Method]

        protected void GetData()
        {
            if (SelectBoxDistrictsProvince.Text == string.Empty)
            {
                DataTable dtDistricts = _clsDistricts.BindGirdDistricts(string.Empty);
                if (dtDistricts != null && dtDistricts.Rows.Count > 0)
                {
                    StoreDistricts.DataSource = dtDistricts;
                    StoreDistricts.DataBind();
                }
                else
                {
                    grDistricts.GetStore().RemoveAll();
                }
            }
            else
            {
                DataTable dtDistricts = _clsDistricts.GetDistrictsFillter(int.Parse(SelectBoxDistrictsProvince.SelectedItem.Value));
                if (dtDistricts != null && dtDistricts.Rows.Count > 0)
                {
                    StoreDistricts.DataSource = dtDistricts;
                    StoreDistricts.DataBind();
                }
                else
                {
                    grDistricts.GetStore().RemoveAll();
                }
            }
        }

        protected void DataDetail(int id)
        {
            DataTable dtDistricts = _clsDistricts.BindGirdDistrictsDetail(id);
            if (dtDistricts != null && dtDistricts.Rows.Count > 0)
            {
                txtDistricts_ID.Text = dtDistricts.Rows[0]["Districts_ID"].ToString();
                txtDistricts_Alias.Text = dtDistricts.Rows[0]["Districts_Alias"].ToString();
                txtDistricts_Name.Text = dtDistricts.Rows[0]["Districts_Name"].ToString();
                txtDistricts_Note.Text = dtDistricts.Rows[0]["Districts_Note"].ToString();
                cbProvince.SetValue(int.Parse(dtDistricts.Rows[0]["Province_Id"].ToString()));
            }
        }

        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var clsDistricts = new Districts_BLL();
            DataTable dtDistricts = clsDistricts.BindGirdDistricts(string.Empty);
            if (dtDistricts != null && dtDistricts.Rows.Count > 0)
            {
                foreach (DataRow dr in dtDistricts.Rows)
                {
                    if (txtDistricts_ID.Text != dr["Districts_ID"].ToString())
                    {
                        if (txtDistricts_Alias.Text == dr["Districts_Alias"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Mã quận huyện đã tồn tại !");
                        }
                        else if (txtDistricts_Name.Text == dr["Districts_Name"].ToString() &&
                                 cbProvince.SelectedItem.Value == dr["Province_ID"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Tên quận huyện thuộc tỉnh này đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }

        protected void InsertDistricts()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Districts_ET
                    {
                        Districts_Alias = txtDistricts_Alias.Text,
                        Districts_Name = txtDistricts_Name.Text,
                        Districts_Note = txtDistricts_Note.Text,
                        Province_Id = int.Parse(cbProvince.SelectedItem.Value)
                    };
                    Districts_BLL.InsertDistricts(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    GetComboBox();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        protected void UpdateDistricts()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Districts_ET
                    {
                        Districts_Id = int.Parse(txtDistricts_ID.Text),
                        Districts_Alias = txtDistricts_Alias.Text,
                        Districts_Name = txtDistricts_Name.Text,
                        Districts_Note = txtDistricts_Note.Text,
                        Province_Id = int.Parse(cbProvince.SelectedItem.Value)
                    };
                    Districts_BLL.UpdateDistricts(obj);
                    WindowsDistricts.Close();
                    clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        private void Province()
        {
            DataTable _dtProvinceFillter = _clsProvince.BindGirdProvince(string.Empty);
            if (_dtProvinceFillter != null && _dtProvinceFillter.Rows.Count > 0)
            {
                StoreDistrictsProvince.DataSource = _dtProvinceFillter;
                StoreDistrictsProvince.DataBind();
            }
            else
            {
                SelectBoxDistrictsProvince.GetStore().RemoveAll();
            }
        } 
        #endregion

        #region [ComboBox]

        protected void GetComboBox()
        {
            var clsNational = new National_BLL();
            DataTable dtNational = clsNational.BindGirdNational(string.Empty);
            if (dtNational != null && dtNational.Rows.Count > 0)
            {
                NationalStore.DataSource = dtNational;
                NationalStore.DataBind();
            }

            var clsDomain = new Domain_BLL();
            DataTable dtDomain = clsDomain.BindGirdDomain(string.Empty);
            if (dtDomain != null && dtDomain.Rows.Count > 0)
            {
                DomainStore.DataSource = dtDomain;
                DomainStore.DataBind();
            }

            var clsProvince = new Province_BLL();
            DataTable dtProvince = clsProvince.BindGirdProvince(string.Empty);
            if (dtProvince != null && dtProvince.Rows.Count > 0)
            {
                ProvinceStore.DataSource = dtProvince;
                ProvinceStore.DataBind();
            }
        }

        protected void NationalSelectIndex_Change(object sender, StoreReadDataEventArgs e)
        {
            cbDomain.ReadOnly = false;
            var clsDomain = new Domain_BLL();
            if (cbNational.SelectedItem.Value != null)
            {
                DataTable dtDomain = clsDomain.BindGirdDomainNational(int.Parse(cbNational.SelectedItem.Value));
                if (dtDomain != null && dtDomain.Rows.Count > 0)
                {
                    DomainStore.DataSource = dtDomain;
                    DomainStore.DataBind();
                }
                else
                {
                    cbNational.Clear();
                    cbDomain.ReadOnly = true;
                    clsFormat.Alert_INFO("Thông báo", "Quốc gia này chưa có miền vui lòng chọn quốc gia khác !");
                }
            }
            else
            {
                cbNational.Clear();
                cbDomain.ReadOnly = true;
                clsFormat.Alert_INFO("Thông báo", "Vui lòng chọn quốc gia !");
            }
        }

        protected void DomainSelectIndex_Change(object sender, StoreReadDataEventArgs e)
        {
            cbProvince.ReadOnly = false;
            var clsProvince = new Province_BLL();
            if (cbDomain.SelectedItem.Value != null)
            {
                DataTable dtProvince = clsProvince.BindGirdProvinceDomain(int.Parse(cbDomain.SelectedItem.Value));
                if (dtProvince != null && dtProvince.Rows.Count > 0)
                {
                    ProvinceStore.DataSource = dtProvince;
                    ProvinceStore.DataBind();
                }
                else
                {
                    cbDomain.Clear();
                    cbProvince.ReadOnly = true;
                    clsFormat.Alert_INFO("Thông báo", "Miền này chưa có tỉnh vui lòng chọn miền khác !");
                }
            }
            else
            {
                cbDomain.Clear();
                cbProvince.ReadOnly = true;
                clsFormat.Alert_INFO("Thông báo", "Vui lòng chọn miền !");
            }
        }

        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }

        #endregion

        #region[ClearTextbox]

        protected void ClearTextBox()
        {
            FormPanelDistricts.Reset();

            txtDistricts_ID.Text = string.Empty;
            txtDistricts_Alias.Text = MaTuDong();
            txtDistricts_Name.Text = string.Empty;
            txtDistricts_Note.Text = string.Empty;

            cbNational.Clear();
            cbDomain.Clear();
            cbDomain.ReadOnly = true;
            cbProvince.Clear();
            cbProvince.ReadOnly = true;
        }

        #endregion

        #region[MaTangTuDong]

        protected string MaTuDong()
        {
            int i;
            DataTable dt = _clsDistricts.BindGirdDistricts(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Districts_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Districts_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Districts_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "QH_00" + i;
        }

        #endregion

        #region[Search]

        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtDistricts = _clsDistricts.BindGirdDistricts(txtSearch.Text);
            if (dtDistricts != null && dtDistricts.Rows.Count > 0)
            {
                StoreDistricts.DataSource = dtDistricts;
                StoreDistricts.DataBind();
            }
        }

        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Districts, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelDistricts.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Districts, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
        //----------Export-Excel---------------
        protected void StoreDistricts_Submit(object sender, StoreSubmitDataEventArgs e)
        {
            var format = FormatTypeDistricts.Value.ToString();
            var xml = e.Xml;
            Response.Clear();
            switch (format)
            {
                case "xml":
                    var strXml = xml.OuterXml;
                    Response.AddHeader("Content-Disposition", "attachment; filename=Districts.xml");
                    Response.AddHeader("Content-Length", strXml.Length.ToString());
                    Response.ContentType = "application/xml";
                    Response.Write(strXml);
                    break;

                case "xls":
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Districts.xls");
                    var xtExcel = new XslCompiledTransform();
                    xtExcel.Load(Server.MapPath("Excel.xsl"));
                    xtExcel.Transform(xml, null, Response.OutputStream);

                    break;

                case "csv":
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Districts.csv");
                    var xtCsv = new XslCompiledTransform();
                    xtCsv.Load(Server.MapPath("Csv.xsl"));
                    xtCsv.Transform(xml, null, Response.OutputStream);

                    break;
            }
            Response.End();
        }
    }
}